<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/7/7
 * Time: 1:39 PM
 */
namespace app\backend\modules\sys\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\common\services\MenuService;
use app\backend\modules\sys\services\PermissionService;
use app\common\exceptions\BizException;
use app\common\models\AdminUser;
use app\common\models\Plugin;
use app\common\services\AutoUpdate;

class PluginController extends BaseController
{
    public function index(){
        return view("backend.sys.plugin.index");
    }
    public function getList(){
        $domain = request()->getHttpHost();
        $data = [];
        $plugins = [];
        $installedList = app('plugins')->getPlugins();
        $installedList->each(function ($item, $key) use (&$data, &$i, &$plugins) {
            $plugins[] = $key;
            $itemArr = $item->toArray();
            $itemArr['status'] = $item->isEnabled() ? true : false;
            $itemArr['new_version'] = 0;
            $itemArr['permit_status'] = '未授权';
            array_push($data,$itemArr);
        });
        //未授权插件数量
        $unPermitPlugin = 0;
        $content = [];
        try{
            $content = (new AutoUpdate())->pluginInstallAuth($domain);
        } catch (\Exception $e){
            //系统未授权
            $content['data'] = [];
        }

        foreach ($content['data'] as $k => $v) {
            foreach ($data as $key => &$value) {
                if ($k == $value['name']) {
                    $value['new_version'] = $v['version'];
                    $value['permit_status'] = $v['status'];
                }
            }
        }
        unset($value);

        foreach ($data as $key => $value) {
            if ('未授权' === $value['permit_status']) {
                $unPermitPlugin++;
            }
        }
        $res['list'] = $data;
        $res['unPermitPlugin'] = $unPermitPlugin;
        $res['countPlugin'] = count($data);
        if (request()->is_search) {
            return $this->searchPlugin($data, request()->search);
        }
        return $this->successJson('',$res);
    }

    public function manage(){
        $name = request()->name;
        $action = request()->action;

        if (app()->environment() == 'production') {
            $this->proAuth($name, $action);
        }
        $pluginService = app('plugins');
        switch ($action) {
            case 'enable':
                $pluginService->enable($name);
                \Artisan::call('config:cache');
                \Cache::flush();
                return $this->successJson('启用成功');
            case 'disable':
                $pluginService->disable($name);
                \Artisan::call('config:cache');
                \Cache::flush();
                return $this->successJson('禁用成功');
            case 'delete':
                if (!\YunCms::$isFounder) {
                    return $this->errorJson('您暂没有权限卸载插件');
                }
                $pluginService->uninstall($name);
                \Artisan::call('config:cache');
                \Cache::flush();
                return $this->successJson('卸载成功');
            default:
                # code...
                break;
        }
    }
    public function batchMange()
    {
        $names = explode(',', request()->names);
        $action = request()->action;
        $pluginService = app('plugins');
        foreach ($names as $name) {
            if (app()->environment() == 'production') {
                $this->proAuth($name, $action);
            }

            switch (request()->action) {
                case 'enable':
                    $pluginService->enable($name);
                    break;
                case 'disable':
                    $pluginService->disable($name);
                    break;
                case 'delete':
                    $pluginService->uninstall($name);
                    break;
                default:
                    return $this->errorJson('操作错误');
                    break;
            }
        }
        switch ($action) {
            case 'enable':
                return $this->successJson('启用成功');
            case 'disable':
                return $this->successJson('禁用成功');
            case 'delete':
                \Artisan::call('config:cache');
                \Cache::flush();
                return $this->successJson('卸载成功');
        }
    }
    private function searchPlugin($data, $search)
    {
        foreach ($data as $key => $value) {
            if ($search['title'] && !strexists($value['title'], $search['title'])) {
                unset($data[$key]);
            }
            if ($search['permit_status'] && !strexists($value['permit_status'], $search['permit_status'])) {
                unset($data[$key]);
            }
            if ($search['update_status'] == '可升级' && $value['version'] == $value['new_version']) {
                unset($data[$key]);
            }
            if ($search['update_status'] == '不可升级' && $value['version'] < $value['new_version']) {
                unset($data[$key]);
            }
            if ($search['status'] === 'enable' && $value['status'] == false) {
                unset($data[$key]);
            }
            if ($search['status'] === 'disable' && $value['status'] == true) {
                unset($data[$key]);
            }
        };
        return $this->successJson('请求成功', array_values($data));
    }


    public function application(){
        $class = $this->getType();
        $data = [];
        $plugins = MenuService::getInstance()->getPluginMenus();//全部插件
        foreach ($plugins as $key => $plugin) {
            $name = explode('.',$plugin['url'])[1];
            if (!$plugin['type']) {
                continue;
            }

            $terminal = app('plugins')->getPlugin($name)->terminal;

            $data[$plugin['type']][$key] = $plugin;
            $data[$plugin['type']][$key]['terminal'] = explode('|',$terminal);
            $data[$plugin['type']][$key]['description'] = app('plugins')->getPlugin($name)->description?:$plugin['name'];
            //todo 图标
            $data[$plugin['type']][$key]['icon_url'] = file_exists(base_path('static/images/plugins/list-icon/' . $plugin['list_icon'] . '.png')) ? "/static/images/plugins/list-icon/{$plugin['list_icon']}.png" : "/static/images/plugins/list-icon/default.png";
            $data[$plugin['type']][$key]['url'] = $this->canAccess($key);

        }
        return view("backend.sys.plugin.application",[
            'plugins' => $plugins,
            'data' => $data,
            'class' => $class
        ]);
    }
    private function proAuth($name, $action)
    {
        if ($action == 'enable') {
            $key = \Setting::get('cms.auth')['key'];
            $secret = \Setting::get('cms.auth')['secret'];

            $res = (new AutoUpdate())->registerChkname($name,$key,$secret);
            if (0 == $res['status']) {
                throw new BizException('应用未授权');
            }
        }
    }
    private function canAccess($item)
    {
        $current_menu = MenuService::getInstance()->getPluginMenus()[$item];
        $url = $current_menu['url'];

        if (\YunCms::$isFounder) {
            return $url;
        }
       //todo
        /*if (PermissionService::checkNoPermission($item) === true) {
            return $url;
        }*/

        if (!isset($current_menu['child'])) {
            return $url;
        }

        $userPermission = AdminUser::userPermissionCache();
        //检测当前 key 下路由是否有权限访问
        foreach ($current_menu['child'] as $key => $value) {

            if ($value['url'] == $current_menu['url'] && in_array($key, $userPermission) && $value['menu'] == 1) {
                return $url;
                break;
            }
            continue;
        }
        //上面条件都不满足时，找第一个有权限访问的路由
        foreach ($current_menu['child'] as $key => $value) {

            if (in_array($key, $userPermission) && $value['menu'] == 1) {
                return $value['url'];
                break;
            }
            continue;
        }
        return 'index.index';
    }
    private function getType()
    {
        return [
            'dividend' => [
                'name' => '入口类',
                'color' => '#F15353',
            ],
            'marketing' => [
                'name' => '营销类',
                'color' => '#f0b652',
            ],
            'business_management' => [
                'name' => '企业管理类',
                'color' => '#f05295',
            ],
            'tool' => [
                'name' => '工具类',
                'color' => '#f59753',
            ]
        ];
    }
}